package com.app.diary.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;

import com.app.diary.Mapp;
import com.app.diary.R;
import com.app.diary.data.UserDataSource;
import com.app.diary.utils.ToastUtils;

/**
 * 注册页面
 */
public class RegisterActivity extends BaseActivity {

    private Toolbar toolbar; // 标题栏控件
    private EditText usernameEditText; // 用户名输入框控件
    private EditText emailEditText; // 邮箱输入框控件
    private EditText passwordEditText; // 密码输入框控件
    private Button registerButton; // 注册按钮控件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        setView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        usernameEditText = findViewById(R.id.username_editText);
        emailEditText = findViewById(R.id.email_editText);
        passwordEditText = findViewById(R.id.password_editText);
        registerButton = findViewById(R.id.register_button);
    }

    /**
     * 设置控件
     */
    private void setView() {
        setSupportActionBar(toolbar);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptRegister();
            }
        });
    }

    /**
     * 尝试注册
     */
    private void attemptRegister() {
        String username = usernameEditText.getText().toString().trim();
        String email = emailEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();

        if (username.isEmpty()) {
            ToastUtils.showShort("请输入用户名");
            return;
        }
        if (email.isEmpty()) {
            ToastUtils.showShort("请输入邮箱");
            return;
        }
        if (password.isEmpty()) {
            ToastUtils.showShort("请输入密码");
            return;
        }

        UserDataSource userDataSource = Mapp.getInstance().getUserDataSource();
        if (userDataSource.registerUser(username, email, password)) {
            ToastUtils.showShort("注册成功");
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            ToastUtils.showShort("注册失败");
        }
    }
}